package users

import (
	"context"
	"database/sql"
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"

	"star/internal/dao"
	"star/internal/model/entity"
	"star/utility"
)

type UserClaims struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

type ResUSER struct {
	Username string `json:"username"`
	Email    string `json:"email"`
	Token    string `json:"token"`
}

func Login(ctx context.Context, username, password string) (res ResUSER, err error) {
	var user entity.Users
	err = dao.Users.Ctx(ctx).Where("username", username).Scan(&user)

	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return ResUSER{}, errors.New("用户不存在")
		}
		return ResUSER{}, err
	}

	if user.Password != encryptPassword(password) {
		return ResUSER{}, errors.New("密码错误")
	}
	UserClaims := &UserClaims{
		ID:       int64(user.Id),
		Username: user.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 6)),
		},
	}
	tokenx := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaims)
	signedToken, err := tokenx.SignedString(utility.JwtKey)
	if err != nil {
		return
	}
	return ResUSER{
		Username: user.Username,
		Email:    user.Email,
		Token:    signedToken,
	}, nil

}
